/**
 * File : TCPServer.java Author : R. Scheurer (EIA-FR) Date : 04.10.2012
 *
 * Description - a simple TCP server template
 *
 */
package sockets.tcp;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

// A class implementing the server's behaviour
public class TCPServer {

    private static final int TCP_SERVER_PORT = 3245; // The server's port number
    static int id = 0; // the client's id

    // The entry point of this TCP server programm, starting the server.
    public static void main(String[] args) {
        try {
            // Socket's creation
            ServerSocket serverSocket = new ServerSocket(TCP_SERVER_PORT);
            serverStarted();
            // For each connectino we get, create a threado handle it
            while (true) {
                Socket s = serverSocket.accept();
                TCPServerThread serverThread = new TCPServerThread(s, id++);
                serverThread.start();
            }

        } catch (IOException ex) {
            Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE,
                                                                 null, ex);
        }
    }
    
    // A method called to display the server's informations as it starts
    private static void serverStarted() {
        System.out.println("Server has started!");
        try {
            InetAddress thisIp = InetAddress.getLocalHost();
            System.out.println("Server's IP = " + thisIp.getHostAddress() +
                    ":" + TCP_SERVER_PORT);
        } catch (Exception e) {
            System.err.println("Could not retrieve "
                    + "server's IP adress. Aborting...");
            System.exit(1);
        }

    }
}
